package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoFormatBinding;
import flc.ast.dialog.FormatDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaMetadataInfo;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;

public class VideoFormatActivity extends BaseAc<ActivityVideoFormatBinding> {

    public static String sVideoPath;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
                mDataBinding.sbProgress.setProgress(mDataBinding.videoView.getCurrentPosition());
            }
            mHandler.postDelayed(mTaskUpdateTime, 500);
        }
    };
    //选择属性
    private String mSelFormat = "";//选择的格式
    private String mNewName = "";//新的名称
    private String mSelFbl = "1080p";//选择的分辨率
    private String mSelMl = "2000kb/s";//选择的码率
    private String mSelZl = "30fps";//选择的帧率
    private int mOriVideoBitrate;
    private FormatDialog formatDialog;
    private FormatDialog resolutionDialog;
    private FormatDialog codeDialog;
    private FormatDialog frameDialog;
    private String mNewPath;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVideoFormatBack.setOnClickListener(v -> onBackPressed());

        mHandler = new Handler();
        mDataBinding.sbProgress.setMax((int) MediaUtil.getDuration(sVideoPath));
        mDataBinding.tvDuration.setText("00:00" + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
        mDataBinding.videoView.setVideoPath(sVideoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
                mDataBinding.ivPlay.setSelected(false);
                mp.seekTo(1);
                stopTime();
            }
        });
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mDataBinding.sbProgress.setMax(mp.getDuration());
                mDataBinding.sbProgress.setProgress(mp.getCurrentPosition());
            }
        });
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivStart.setOnClickListener(this);
        mDataBinding.tvFormat.setOnClickListener(this);
        mDataBinding.tvName.setOnClickListener(this);
        mDataBinding.tvResolution.setOnClickListener(this);
        mDataBinding.tvCode.setOnClickListener(this);
        mDataBinding.tvFrame.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        if (!FastClickUtil.isFastClick()) {
            switch (v.getId()) {
                case R.id.ivPlay://播放
                    if (mDataBinding.videoView.isPlaying()) {
                        mDataBinding.ivPlay.setSelected(false);
                        mDataBinding.videoView.pause();
                        stopTime();
                    } else {
                        mDataBinding.ivPlay.setSelected(true);
                        mDataBinding.videoView.start();
                        startTime();
                    }
                    break;
                case R.id.tvFormat://目标格式
                    showFormatDialog();
                    break;
                case R.id.tvName://文件名
                    showRenameDialog();
                    break;
                case R.id.tvResolution://分辨率
                    showResolutionDialog();
                    break;
                case R.id.tvCode://码率
                    showCodeDialog();
                    break;
                case R.id.tvFrame://帧率
                    showFrameDialog();
                    break;
                case R.id.ivStart:
                    startConvert();
                    break;
            }
        }
    }

    @Override
    protected void initData() {
        mNewName = FileUtils.getFileNameNoExtension(sVideoPath);
        mDataBinding.tvName.setText(mNewName);
        mDataBinding.tvResolution.setText(mSelFbl);
        mDataBinding.tvCode.setText(mSelMl);
        mDataBinding.tvFrame.setText(mSelZl);
        //获取视频码率
        getCodeRate();
    }

    private void showRenameDialog() {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_name);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                mNewName = name;
                if (!TextUtils.isEmpty(mNewName)) {
                    mDataBinding.tvName.setText(mNewName);
                }
            }
        });
        dialog.show();
    }

    private void showFormatDialog() {
        if (formatDialog == null) {
            formatDialog = new FormatDialog(mContext);
        }
        formatDialog.setType(0);
        formatDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvFormat.setText(name);
                mSelFormat = name;
            }
        });
        formatDialog.show();
    }

    private void showResolutionDialog() {
        if (resolutionDialog == null) {
            resolutionDialog = new FormatDialog(mContext);
        }
        resolutionDialog.setType(1);
        resolutionDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvResolution.setText(name);
                mSelFbl = name;
            }
        });
        resolutionDialog.show();
    }

    private void showCodeDialog() {
        if (codeDialog == null) {
            codeDialog = new FormatDialog(mContext);
        }
        codeDialog.setType(2);
        codeDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvCode.setText(name);
                mSelMl = name;
            }
        });
        codeDialog.show();
    }

    private void showFrameDialog() {
        if (frameDialog == null) {
            frameDialog = new FormatDialog(mContext);
        }
        frameDialog.setType(3);
        frameDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvFrame.setText(name);
                mSelZl = name;
            }
        });
        frameDialog.show();
    }

    private void getCodeRate() {
        RxUtil.create(new RxUtil.Callback<MediaMetadataInfo>() {
            @Override
            public void doBackground(ObservableEmitter<MediaMetadataInfo> emitter) {
                MediaMetadataInfo info = MediaUtil.getMediaMetadataInfo(sVideoPath);
                emitter.onNext(info);
            }

            @Override
            public void accept(MediaMetadataInfo info) {
                if (info != null) {
                    mOriVideoBitrate = info.getBitrate();
                }
            }
        });
    }

    private void startConvert() {
        if (TextUtils.isEmpty(mSelFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(mNewName)) {
            ToastUtils.showShort(R.string.please_input_file_name);
        } else if (TextUtils.isEmpty(mSelFbl)) {
            ToastUtils.showShort(R.string.please_sel_fbl);
        } else if (TextUtils.isEmpty(mSelZl)) {
            ToastUtils.showShort(R.string.please_sel_zl);
        } else if (TextUtils.isEmpty(mSelMl)) {
            ToastUtils.showShort(R.string.please_sel_ml);
        } else {
            mDataBinding.ivStart.setEnabled(false);
            //整理参数
            float fbl = getFbl();
            int ml = getMl();
            String format = getFormat();
            compressVideo(fbl, ml, format);//修改参数其实就是压缩视频
        }
    }

    private void compressVideo(float fbl, int ml, String format) {
        int width = (int) (mDataBinding.videoView.getWidth() * fbl);
        int height = (int) (mDataBinding.videoView.getHeight() * fbl);
        EditorHolder.editor().videoCompress(sVideoPath, width, height, ml, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                mDataBinding.ivStart.setEnabled(true);
                saveVideo(outFilePath, format);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                mDataBinding.ivStart.setEnabled(true);
                ToastUtils.showShort(R.string.conv_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.conv_ing) + progress + "%");
            }
        });
    }


    private void saveVideo(String path, String format) {
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(path, filePath);
                emitter.onNext(filePath);
            }

            @Override
            public void accept(String savePath) {
                dismissDialog();
                //重命名
                FileUtils.rename(savePath, mNewName + format);
                mNewPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + mNewName + format;
                ToastUtils.showShort(getString(R.string.convert_success));
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, mNewPath);
                mDataBinding.ivStart.setEnabled(true);
                startActivity(HomeActivity.class);
            }
        });
    }


    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = VideoFormat.MP4.getSuffix();
        if (mSelFormat.equals("mp4")) {
            format = VideoFormat.MP4.getSuffix();
        } else if (mSelFormat.equals("avi")) {
            format = VideoFormat.AVI.getSuffix();
        } else if (mSelFormat.equals("mkv")) {
            format = VideoFormat.MKV.getSuffix();
        } else if (mSelFormat.equals("3gp")) {
            format = VideoFormat.THREE_GP.getSuffix();
        } else if (mSelFormat.equals("mov")) {
            format = VideoFormat.MOV.getSuffix();
        }
        return format;
    }

    //根据选择的码率获取码率比例
    private int getMl() {
        float mBitrateScale = 1.0f;
        if (mSelMl.equals("250kps")) {
            mBitrateScale = 0.2f;
        } else if (mSelMl.equals("1000kb/s")) {
            mBitrateScale = 0.4f;
        } else if (mSelMl.equals("1500kb/s")) {
            mBitrateScale = 0.6f;
        } else if (mSelMl.equals("2000kb/s")) {
            mBitrateScale = 0.8f;
        } else if (mSelMl.equals("3000kb/s")) {
            mBitrateScale = 1.0f;
        }
        return (int) (mOriVideoBitrate * mBitrateScale);
    }


    //根据选择的分辨率获取分辨率比例
    private float getFbl() {
        float mResolutionScale = 1.0f;
        if (mSelFbl.equals("2k")) {
            mResolutionScale = 1.0f;
        } else if (mSelFbl.equals("1080p")) {
            mResolutionScale = 0.8f;
        } else if (mSelFbl.equals("720p")) {
            mResolutionScale = 0.6f;
        } else if (mSelFbl.equals("540p")) {
            mResolutionScale = 0.5f;
        } else if (mSelFbl.equals("480p")) {
            mResolutionScale = 0.4f;
        }
        return mResolutionScale;
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTime();
        if (!TextUtils.isEmpty(mNewPath)) {
            FileUtils.delete(mNewPath);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mDataBinding.videoView.seekTo(1);
    }

}